Skip to main content
Version: Next

Integrated Libraries

This category specifies protocols imported from the outside libraries.

warning

WORK IN PROGRESS: This manual is currently being updated and may not contain all the necessary information.

Introduction

The following libraries were implemented:

note

Beware, that linked documentation is not always complete and the article tries to link these for cross-reference purposes

note

Beware, that while the aforementioned libraries are implemented, not all the functions may be enabled. Consult the rest of the article for further details.

eLua Bit Module library

Since Lua doesn't have (yet) built-in capabilities for bit operations, the bit module was added to eLua to fill this gap. It is based on the bitlib library written by Reuben Thomas (slightly adapted to eLua) and provides basic bit operations (like setting and clearing bits) and bitwise operations.

Overview

FunctionShort DescriptionNote
bit.bnotbitwise negation
bit.bandbitwise AND
bit.borbitwise OR
bit.bxorexclusive bitwise OR
bit.lshiftlogical bitwise left shift
bit.rshiftlogical bitwise right shift
bit.arshiftarithmetic bitwise right shift
bit.bitgenerate a bit number
bit.setset bits in a number
bit.clearset bits in a number
bit.issetcheck if the value in bits is set
bit.isclearcheck if the value in bits is clear

bit.bnot(value)


print(bit.bnot(0))

Bitwise negation, equivalent to ~value in C.

Arguments

  • Argument 1: value

    • the bitwise to negate

Return

  • value: (integer)

    • the bitwise negated value of the number

Example

print(bit.bnot(0))            --> -1
print(bit.bnot(-1)) --> 0
print(bit.bnot(0xffffffff)) --> 0

bit.band(value1, value2, ...)


print(bit.band(0x12345678, 0xff))

Returns bitwise AND of all of its arguments. Note that more than two arguments are allowed.

Arguments

  • Argument 1: value 1
  • Argument 2: value 2

Optional

  • Argument 3 (optional): value 3
  • Argument 4 (optional)...

Return

  • value: (integer) - the bitwise AND of all the arguments

Examples

print(bit.band(1, 2, 4, 8))              --> 0
print(bit.band(0x12345678, 0xff)) --> 120

Lua Script Example

bb=bit.band
function rcntr() local r = bb(g(2)+1) sv(2, r) return b(r) end

bit.bor(value1, value2, ...)


print(bit.bor(0x12345678, 0xff))

Returns bitwise OR of all of its arguments. Note that more than two arguments are allowed.

Arguments

  • Argument 1: value 1
  • Argument 2: value 2

Optional

  • Argument 3 (optional): value 3
  • Argument 4 (optional)...

Return

  • value: (integer) - the bitwise OR of all the arguments

Examples

print(bit.bor(1, 2, 4, 8))		--> 15
print(bit.bor(0x12345678, 0xff)) --> 305420031

Lua Script Example

if nextWR == 1 then
sendFrames(true)
f = b(0xF4) .. rcntr()
i = 1
k = 0
jj = 1
while k == 0 do
B = 0
for j = 0, 7 do
if i > FLen then
k = 1
jj = j
break
end
B = bit.bor(B, bit.lshift(tbi(i), j))
i = i + 1
end
if jj ~= 0 then
f = f .. b(B)
end
end

bit.bxor(value1, value2, ...)


print(bit.bxor(0x12345678, 0xff))

Returns exclusive bitwise OR of all of its arguments. Note that more than two arguments are allowed.

Arguments

  • Argument 1: value 1
  • Argument 2: value 2

Optional

  • Argument 3 (optional): value 3
  • Argument 4 (optional)...

Return

  • value: (integer) - the exclusive bitwise OR of all the arguments

Examples

print(bit.bxor(1, 2, 4, 8))		--> 15
print(bit.bxor(0x12345678, 0xff)) --> 305419911

Lua Script Example

elseif cmd == 5 then
len = wf("show-length")
idchs = 0
for i=1,len do
_,tmp=pu(wf("show-index", i), "<I")
idchs = bit.bxor(idchs, tmp)
end

bit.lshift(value, shiftPosition)


print(bit.lshift(1, 8))

Returns the bitwise logical left-shift of its first argument by the number of bits given by the second argument. Logical shifts treat the first argument as an unsigned number and shift in 0-bits.

Arguments

  • Argument 1: value - the value to be shifted to left
  • Argument 2: shiftPosition - the position we want to shift it to

Return

  • value: (integer) - the number shifted left

Examples

print(bit.lshift(1, 0))              --> 1
print(bit.lshift(1, 8)) --> 256
print(bit.lshift(1, 40)) --> 256
print(bit.lshift(0x87654321, 12)) --> 1412567040

Lua Script Example

if nextWR == 1 then
sendFrames(true)
f = b(0xF4) .. rcntr()
i = 1
k = 0
jj = 1
while k == 0 do
B = 0
for j = 0, 7 do
if i > FLen then
k = 1
jj = j
break
end
B = bit.bor(B, bit.lshift(tbi(i), j))
i = i + 1
end
if jj ~= 0 then
f = f .. b(B)
end
end

bit.rshift(value, shiftPosition)


print(bit.rshift(256, 8))

Returns the bitwise logical right-shift of its first argument by the number of bits given by the second argument. Logical shifts treat the first argument as an unsigned number and shift in 0-bits.

Arguments

  • Argument 1: value - the value to be shifted right
  • Argument 2: shiftPosition - the position we want to shift it to

Return

  • value: (integer) - the number shifted right

Examples

print(bit.rshift(256, 8))            --> 1
print(bit.rshift(-256, 8)) --> 16777215
print(bit.rshift(0x87654321, 12)) --> 554580

bit.arshift(value, shiftPosition)


print(bit.arshift(-256, 8))

Returns the bitwise arithmetic right-shift of its first argument by the number of bits given by the second argument. Arithmetic right-shift treats the most-significant bit as a sign bit and replicates it.

Arguments

  • Argument 1: value - the value to be shifted right
  • Argument 2: shiftPosition - the position we want to shift it to

Return

  • value: (integer) - the number shifted right

Examples

print(bit.arshift(256, 8))           --> 1
print(bit.arshift(-256, 8)) --> -1
print(bit.arshift(0x87654321, 12)) --> 554580

bit.bit(position)


print(bit.bit(4))

Generate a number with a 1 bit (used for mask generation), Equivalent to 1 < position in C.

Arguments

  • Argument: position - position of the bit that will be set to 1

Return

  • value: (integer) - a number with only one 1 bit at position (the rest are set to 0)

Examples

print(bit.bit(4))    --> 16

bit.set(value, position1, position2, ...)


print(bit.set(100, 1, 2, 3))

Sets bits in a number.

Arguments

  • Argument 1: value - the base number
  • Argument 2: position1 - position of the first bit to set (note: indexing starts at 1 in Lua)

Optional

  • Argument 3: position2 - position of the second bit to set (note: indexing starts at 1 in Lua)
  • Argument 4...

Return

  • value: (integer) - the number with the bit(s) set in the given position(s)

Examples

print(bit.set(100, 1))      --> 102
print(bit.set(100, 1, 2, 3)) --> 110

Lua Script Example

function makeHeader(finalFlag, messageNum)
local header = getIMEI()
header = header .. framecounter("h")
framecounter("i")

header = header .. pack.pack('b', plport)
header = header .. getSignal()

if(finalFlag == 1) then
messageNum = bit.set(messageNum, 6)
end

header = header .. pack.pack('>b2', 0x10, messageNum)
return header
end

bit.clear(value, position1, position2, ...)


print(bit.clear(100, 10, 5, 1))

Clears bits in a number.

Arguments

  • Argument 1: value - the base number
  • Argument 2: position1 - position of the first bit to clear (note: indexing starts at 1 in Lua)

Optional

  • Argument 3: position2 - position of the second bit to clear (note: indexing starts at 1 in Lua)
  • Argument 4...

Return

  • value: (integer) - the number with the bit(s) cleared in the given position(s)

Examples

print(bit.clear(100, 10, 5, 1)) --> 68

bit.isset(value, position)


print(bit.isset(1, 1111))

Tests if a given bit is set - basically opposite of bit.isclear().

Arguments

  • Argument 1: value - the value to test
  • Argument 2: position - bit position to test (note: indexing starts at 1 in Lua)

Return

  • value: (boolean) - true if the bit at the given position is 1, otherwise false

Examples

print(bit.isset(2, 0))    --> false
print(bit.isset(1, 1111)) --> true

bit.isclear(value, position)


print(bit.isclear(2, 0))

Tests if a given bit is cleared - basically opposite of bit.isset().

Arguments

  • Argument 1: value - the value to test
  • Argument 2: position - bit position to test (note: indexing starts at 1 in Lua)

Return

  • value: (boolean) - true if the bit at the given position is 0, otherwise false

Examples

print(bit.isclear(2, 0))    --> true
print(bit.isclear(1, 1111)) --> false

bit.tohex(value, absoluteValue)


print(bit.tohex(-1, -8))

Converts its first argument to a hex string. The number of hex digits is given by the absolute value of the optional second argument. Positive numbers between 1 and 8 generate lowercase hex digits. Negative numbers generate uppercase hex digits. Only the least-significant 4*|n| bits are used. The default is to generate 8 lowercase hex digits.

Arguments

  • Argument 1: value - the value that is converted to a hex string
  • Argument 2 (optional): absoluteValue - number of hex digits: from -8 to 8; positive generates lowercase hex digits; negative generates uppercase hex digits

Return

  • value: (hex string)

Examples

print(bit.tohex(1))              --> 00000001
print(bit.tohex(-1)) --> ffffffff
print(bit.tohex(0xffffffff)) --> ffffffff
print(bit.tohex(-1, -8)) --> FFFFFFFF
print(bit.tohex(0x21, 4)) --> 0021
print(bit.tohex(0x87654321, 4)) --> 4321

bit.rol(value1, value2)


print(bit.rol(0x12345678, 12))

Returns the bitwise left rotation of its first argument by the number of bits given by the second argument. Bits shifted out on one side are shifted back in on the other side. Only the lower 5 bits of the rotate count are used (reduces to the range [0..31]).

Arguments

  • Argument 1: value - the value that is modified
  • Argument 2: shiftCount - the number of bits to shift it to the left side

Return

  • value: (integer) - bitwise left rotation

Examples

print(bit.rol(0x12345678, 12))   --> 1164411171

bit.ror(value1, value2)


print(bit.ror(0x12345678, 12))

Returns the bitwise right rotation of its first argument by the number of bits given by the second argument. Bits shifted out on one side are shifted back in on the other side. Only the lower 5 bits of the rotate count are used (reduces to the range [0..31]).

Arguments

  • Argument 1: value - the value that is modified
  • Argument 2: shiftCount - the number of bits to shift it to the right side

Return

  • value: (integer) - bitwise right rotation

Examples

print(bit.ror(0x12345678, 12))   --> 1736516421

Lua Math Library

Library used mainly for pre-determined mathematical functions.

info

Note, that the converters use only integers for mathematical functions, therefore only some of them are available to use.

Overview

FunctionShort DescriptionNote
math.absabsolute value
math.hugereturns maximum numerical value
math.maxpick the highest value
math.minpick the lowest value
math.powpower
math.randomrandom number
math.randomrandom number with bottom ceiling
math.randomseedseed randomization
math.sqrtsquare root

math.abs(integer)


print(math.abs(-5))

The abs() function in Lua's math library returns the absolute value of a given number.

Arguments

  • Argument 1: integer

Return

  • value: (integer) - the absolute value of the argument

Examples

var value = -5
var absValue = math.abs(value)
print(absValue) --> 5

Lua Script Example

function GetTimestamp()
local sign, zone, Y, m, d, H, M, S, z = "", "", api.getTimeDate(1)
if z then
sign, z = z < 0 and "-" or "+", math.abs(z)

math.huge


print(math.huge)

This creates a maximum possible number, in our case, a maximum value of an integer.

Return

  • value: (integer: 2147483647)

Examples

var intMax = math.huge
print(intMax) --> 2147483647

math.max(integer1, integer2, ...)


print(math.max(54, 15, 78))

The max() function picks the highest value from the individual values specified in the arguments.

Arguments

  • Argument 1: integer
  • Argument 2 (optional): integer

Optional

  • Argument 3 (optional): integer
  • Argument 4...

Return

  • value: (integer) - the highest value of the arguments

Examples

var n1 = 54
var n2 = 15
var n3 = 78

print(math.max(n1, n2, n3)) --> 78

Lua Script Example

function Validate(name) return math.max(var[name].min, math.min(var[name].max, api.getVar(var[name].id) or -1)) end

math.min(integer1, integer2, ...)


print(math.min(54, 15, 78))

The min() function picks the lowest value from the individual values specified in the arguments.

Arguments

  • Argument 1: integer
  • Argument 2 (optional): integer

Optional

  • Argument 3 (optional): integer
  • Argument 4...

Return

  • value: (integer) - the lowest value of the arguments

Examples

var n1 = 54
var n2 = 15
var n3 = 78
print(math.min(n1, n2, n3)) --> 15

Lua Script Example

function Validate(name) return math.max(var[name].min, math.min(var[name].max, api.getVar(var[name].id) or -1)) end

math.pow(intToBeRaised, intRaiseWith)


print(math.pow(2, 3))

A number(x) in the first argument raised to the power of a number(y) in the second argument (you can also use x ^ y).

Arguments

  • Argument 1: integer
  • Argument 2: integer

Return

  • value: (integer) - a number raised to a certain power

Examples

var n1 = 54
var n2 = 15
var n3 = 78

print(math.pow(n1, n2, n3))

math.random(intMaxValue)


print(math.random(10))

Creates a random value with the argument being the maximum value and starting at 1 by default.

note

Note, that api.randInt() is commonly used and ideal to generate random numbers, but this function is also possible. This api.randInt() is not available on NB-IoT devices, so there you would use this one.

Arguments

  • Argument 1: integer - maximum value the random number can have

Return

  • value: (integer) - a random number

Examples

print(math.random(10)) --> 1 to 10

math.random(intMinValue, intMaxValue)


print(math.random(10, 120))

Creates a random value, with the arguments being the minimum and maximum value.

note

Note, that api.randInt() is commonly used and ideal to generate random numbers, but this function is also possible. This api.randInt() is not available on NB-IoT devices, so there you would use this one.

Arguments

  • Argument 1: integer - minimal value the number can have
  • Argument 2: integer - maximal value the number can have

Return

  • value: (integer) - a random number

Examples

print(math.random(10, 120)) --> 10 to 120

math.randomseed(integer)


math.randomseed(44)

Seeds the random number generator with an integer.

Arguments

  • Argument 1: integer
warning

Seeding with os.time() is not possible on our devices.

Examples

math.randomseed(44)
print(math.random(10)) --> 1 to 10 based on the seed

math.sqrt(integer)


print(math.sqrt(25))

Calculates the square root of a number, but converted to an integer.

Arguments

  • Argument 1: integer - a number we want a square root of

Return

  • value: (integer) - a square root of a number converted to integer

Examples

print(math.sqrt(25)) --> 5

Lua String Library

This library enables additional possibilities for working with text - strings and characters.

Overview

FunctionShort DescriptionNote
string.bytecharacter numerical code on the first pos
string.bytecharacter numerical code on a specific pos
string.findstring pattern search
string.formatcreating formatted strings
string.gmatchreturn iterator
string.gsubreplacing substring with a substring
string.lenmeasuring string length
string.lowerlowercase conversion
string.upperuppercase conversion
string.match-
string.reprepeating a string
string.reversereversing a string
string.subextracting a substring
string.index-

string.byte(stringOrChar)


print(string.byte('a'))

Returns the numerical code of the first character of the string.

Arguments

  • Argument 1: string or character

Return

  • value: (integer) - a numerical value of the first character in the argument

Examples

print(string.byte('a')) --> 97

string.byte(string, intPosition)


print(string.byte("Lua123", 3))

Returns the numerical code of the character in the string on a specific position.

Arguments

  • Argument 1: string - string, from which we want to extract a character code
  • Argument 2: integer - position of said character (note: there is a way to index from either side; indexing starts at 1 in Lua)

Return

  • value: (integer) - a numerical value of the character

Examples

-- third character
print(string.byte("Lua123", 3)) --> 97

-- first character from last
print(string.byte("Lua123", -1)) --> 51

-- second character
print(string.byte("Lua123", 2)) --> 117

-- second character from last
print(string.byte("Lua123", -2)) --> 50

Lua Script Example

temper = string.byte(answer, 4)*256+string.byte(answer, 5)
humid = string.byte(answer, 6)*256+string.byte(answer, 7)

string.find(string, strImSearchingFor, intSearchIndex, boolPattern)


print(string.find("hello world", "world"))

Searches for a specific string or character in a string and returns its position if found.

Arguments

  • Argument 1: string - string I am searching through
  • Argument 2: string or character - string or char I am searching for
  • Argument 3 (optional): integer - the position to start the search at (note: indexing starts at 1 in Lua; default is 1)

Optional

  • Argument 4 (optional): boolean - whether we want to use pattern matching or not (default is false)

Return

  • value: (integer) - starting index of the string we search for OR nil if there are no search results
note

Note, that Lua indexing starts at 1. That means that index of position e.g. 5 is indeed on fifth position, unlike in most languages, where it would be sixth.

Examples

local sentence = 'hello world'
local search1 = string.find(sentence, "hello")
print(search1) --> 1
search1 = string.find(sentence, "world")
print(search1) --> 7

string.format(strFormat, value1, value2, ...)


print(string.format("Hello, my name is %s", "Angel"))

The .format() function is used to create formatted strings by replacing placeholders with specified values.

Arguments

  • Argument 1: string - specification of the string which has dynamic values to be replaced
  • Argument 2: string, char, or integer - element to be placed in the first position

Optional

  • Argument 3: string, char, or integer - element to be placed in the second position
  • Argument 4...

Return

  • value: (string) - final string with all the values inserted

Examples

local name = "Angel"
local height = 5.587
local age = 20

local formatted = string.format("Hello, my name is %s, I am %.1f ft tall and I am %d years old.", name, height, age)
print(formatted) --> Hello, my name is Angel, I am 5.6 ft tall and I am 20 years old.

Lua Script Example

local function ps(id, r, op) p(string.format("%08X", id), op.." @", r) end

string.gmatch(string, pattern)


for word in string.gmatch("Hello Lua user", "%a+") do print(word) end

Returns an iterator function for returning the next capture from a pattern over a string. If there is no capture, the whole match is produced.

Arguments

  • Argument 1: string - string which you want to match
  • Argument 2: pattern - pattern to match

Return

  • value: iterator function

Examples

for word in string.gmatch("Hello Lua user", "%a+") do print(word) end
--> Hello
--> Lua
--> user

Lua Script Example

imsi = ""
function tx(d, tout, rp)
if withIMSI then
if imsi == "" then
local r = at("IMSI?", 5000)
for val in string.gmatch(r, "([0-9]+)") do
imsi = val
end
end
end

string.gsub(strToModify, strToBeReplaced, strThatIsReplacing)


print(string.gsub("Lua Tutorial", "Tutorial", "Language"))

Modifies a part of string by replacing it with another string.

Arguments

  • Argument 1: string - string that needs to have part of it replaced
  • Argument 2: string - part of the string that we want to replace
  • Argument 3: string - what we are going to replace it with

Return

  • value: (string) - returns a modified string

Examples

string = "Lua Tutorial"

-- replacing strings
newstring = string.gsub(string, "Tutorial", "Language")
print("The new string is "..newstring) --> The new string is Lua Language

Lua Script Example

local c = string.gsub(str, ".*apiexec:\"([^\"]+)\".*", "%1")

string.len(stringToMeasure)


print(string.len("five"))

Returns a length of the string in an integer representing the amount of characters it contains.

Arguments

  • Argument 1: string - a string we want to measure

Return

  • value: (integer) - how long the string is

Examples

local length = string.len("five")
print(length) --> 4

Lua Script Example

function getbytelen(payload) -- generates payload length
local len = string.len(payload)
local lenv = pack.pack('>H', len) -- 'H' stand for unsigned short
return lenv
end

string.lower(string)


print(string.lower("HELLO"))

Converts a string to lowercase.

Arguments

  • Argument 1: string - a string we want to convert to lowercase

Return

  • value: (string) - a lowercase string

Examples

print(string.lower("HELLO")) --> hello

string.upper(string)


print(string.upper("hello"))

Converts a string to uppercase.

Arguments

  • Argument 1: string - a string we want to convert to uppercase

Return

  • value: (string) - an uppercase string

Examples

print(string.upper("hello")) --> HELLO

string.rep(strToRepeat, intRepeatTimes)


print(string.rep("hi", 3))

Duplicates and concatenates a string indicated the number of times.

Arguments

  • Argument 1: string - a string to repeat
  • Argument 2: integer - the amount of times to repeat Argument 1

Return

  • value: (string) - string concatenated the amount of times it was repeated

Examples

print(string.rep("hi", 3)) --> hihihi

Lua Script Example

function padString(str, length, paddingChar)
local padding = length - #str
if padding > 0 then
return str .. string.rep(paddingChar, padding)
else
return str
end
end

string.reverse(string)


print(string.reverse("string"))

Reverses a string.

Arguments

  • Argument 1: string - a string we want to reverse

Return

  • value: (string) - reversed string

Examples

print(string.reverse("string")) --> gnirts

string.sub(strOriginal, intStartIndex, intEndIndex)


print(string.sub("this is a string", 8))

Extract a substring from a string.

Arguments

  • Argument 1: string - a string we want to create a substring from
  • Argument 2: integer - at what index we want to start cutting the substring (note: indexing starts at 1 in Lua)

Optional

  • Argument 3 (optional): integer - at what index we want to end cutting the substring (note: indexing starts at 1 in Lua; by default, substring ends at the same point as the original)

Return

  • value: (string) - a cut out string from the original string

Examples

print(string.sub("this is a string", 8)) --> a string
print(string.sub("this is a string", 3, 7)) --> is is

Lua Script Example

cnt, req = api.stdin("readuntil", 100) -- maximum 100 characters, read until '\n'
req = string.sub(req, 1, -2) -- drop last character - newline
if req == "r" then
print("reset...")
api.nbAT("AT", 2)
elseif req == "w" then
print("wake up...")
api.nbAT("AT", 1)
else
print("> " .. req)
api.nbAT(req)
end

Standard Lua Functions

These are the standard Lua functions available on our devices. Unlike the rest of the libraries, they do not require a prefix.

Overview

FunctionShort DescriptionNote
assertspecific error trigger
collectgarbagemanual garbage collecting
errorcustom error message
gcinfocurrent memory use
getfenvcurrent environment table
getmetatablemetatable of an object
setmetatable-
loadstringcompile a piece of code
nextkey value pair in a table
pcallprotected function calling
printprint a string
rawequalcompare two values
rawgetget a table value
rawsetset a table value
selectreturn an indexed value
selectreturn the argument count
setfenvset environment
tonumberconvert to number
tostringconvert to string
typereturn a data type
unpackunpack table
xpcallfunction with an error handler

assert(triggerCondition, strErrorMessage)


assert(tonumber(n), "invalid input")

A method that triggers a custom error message when specific condition is met.

Arguments

  • Argument 1: boolean - if this condition is false (or nil), then the error message displays
  • Argument 2: string - the error message that gets displayed

Return

  • value: (boolean) - if false, error message is triggered

Examples

n = io.read()
assert(tonumber(n), "invalid input: " .. n .. " is not a number")

collectgarbage(strCommand)


collectgarbage("collect")

Allows for manual control of (otherwise automatic) garbage collecting.

Arguments

  • Argument 1 (optional): string - by default (no argument), triggers "collect" - one complete cycle of garbage collection; allows to trigger specific actions based on specific string commands

Return

Examples

local table = {4, 5, 5, 45}
collectgarbage() -- table is not affected
print(table) --> 4 5 5 45
table = nil
collectgarbage() -- manual disposal of table

error(strErrorMessage)


error("You do not have sufficient funds")

Triggers an error with a custom message.

Arguments

  • Argument 1: string - a message we want to display when the error triggers

Examples

var wallet = 10
var withdraw = -11
if withdraw > wallet then
error("You do not have sufficient funds in your wallet, your current credit is "..wallet) -- this error message pops up
end

gcinfo()


print(gcinfo())

Returns a value of Kb that are currently in dynamic memory use. Basically the same functionality as collectgarbage("count").

Return

  • value: (integer) - value in Kb of used dynamic memory

Examples

print(gcinfo().." Kb are currently in use") --> 103 Kb are currently in use

getfenv(table, intIndex)


funcTable = getfenv(func)

Returns the current environment table.

Arguments

  • Argument 1 (optional): integer - the default value is 1; 1 would be the currently running function, 2 is its parent and so on...

Return

  • value: (table) - returns the current environment table where "global" variables are stored

Examples

funcTable = getfenv(func)
print(funcTable) --> table: 02072780

getmetatable(object)


getmetatable(_G)

Returns the metatable for the object.

Arguments

  • Argument 1: object - the metatable of an object

Return

  • value: nil if no metatable; the value of the __metatable field of the metatable, if any; the metatable of the object

Examples

getmetatable(_G) --> nil

loadstring(strCode)


f = loadstring("print 'hello, world'")

Compiles a string of Lua code.

Arguments

  • Argument 1: string - a string to be compiled

Return

  • value: (function) - parses the string and returns the compiled chunk as a function, does not execute it; can be executed by adding () after the variable we store the string into

Examples

f = loadstring("print 'hello, world'")
f() --> hello, world

next(table, intIndex)


for i, word in next, words do print(i, word) end

Returns next key / value pair in a table.

Arguments

  • Argument 1: table - the table we want to work with
  • Argument 2 (optional): integer - if we want to start at a specific index, we specify it here (note: indexing starts at 1 in Lua)

Return

  • value: (integer and value) - returns the next index; if index is nil (the default), returns the first pair; when called with the last index of the table (or with an index of nil for an empty table) it does not return anything

Examples

words = { "hello", "world" }

for i, word in next, words do
print(i, word)
end

-->
--[[
1 hello
2 world
]]--

print(argument1, argument2, ...)


print("Hello", "world", 123)

Prints its arguments to a string, primarily used for feedback.

Arguments

  • Argument 1: anything - prints out argument 1
  • Argument 2 (optional): anything - prints out argument 2
  • Argument 3...

Return

  • value: (string) - prints all the values as text; when multiple arguments are passed in, there will be space between them

Examples

print("Hello", "world", 123, assert) --> Hello world 123 function: 02071C00

Lua Script Example

function onStartup()
buf, err, ack, wake = api.getGUIContext()
print("Starting up LUA interface...")

rawequal(value1, value2)


print(rawequal(1, 0x01))

Compares two values and determines whether they are equal and returns true or false.

Arguments

  • Argument 1: value - first value to be compared with the second one
  • Argument 2: value - second value to be compared with the first one

Return

  • value: (boolean) - true if the values are equal, else false

Examples

print(rawequal(1, 0x01)) --> true

Lua Script Example

function onStartup()
buf, err, ack, wake = api.getGUIContext()
print("Starting up LUA interface...")

rawget(table, intIndex)


print(rawget(tab, 2))

Gets the value of a table item without invoking metamethods.

Arguments

  • Argument 1: table - the table we want to get the value from
  • Argument 2: integer - the index of the value we are trying to get (note: indexing starts at 1 in Lua)

Return

  • value: value of a table item without invoking metamethods

Examples

local tab = {"hi", "hello", "oi"}
print(rawget(tab, 2)) --> hello

rawset(table, intIndex, newValue)


rawset(tab, 2, "holla")

Sets the value of a table item without invoking metamethods.

Arguments

  • Argument 1: table - the table we want to set the value in
  • Argument 2: integer - the index of the value we are trying to set (note: indexing starts at 1 in Lua)
  • Argument 3: value - the new value we are trying to set

Return

Examples

local tab = {"hi", "hello", "oi"}
rawset(tab, 2, "holla") --> changing hello to holla
print(rawget(tab, 2)) --> holla

select(intIndex, value1, value2, ...)


print(select(1, 2, "hi", {4, 5, 2}))

Returns all the values starting with a specific index. If I have 4 arguments with value, it would return 2 arguments if I use index of 3.

Arguments

  • Argument 1: integer - at what index does the selection start (note: indexing starts at 1 in Lua)
  • Argument 2: value

Optional

  • Argument 3 (optional): value
  • Argument 4...

Return

  • value: arguments - returns all the values starting with the index; the index can be negative, in such case, it starts with the last value and ends with the first

Examples

print(select(1, 2, "hi", {4, 5, 2})) --> 2  hi  table: 0x200052c4
print(select(-2, "a", "b", "c", "d")) --> c d

select("#", value1, value2, ...)


print(select("#", 2, "hi", {4, 5, 2}))

Returns the amount of arguments passed after the operator. If I have 4 arguments with value, it would return 4.

Arguments

  • Argument 1: "#" - makes the function count the amount of values in the following argument
  • Argument 2: value

Optional

  • Argument 3 (optional): value
  • Argument 4...

Return

  • value: (integer) - returns the amount of arguments used except the argument 1

Examples

print(select("#", 2, "hi", {4, 5, 2})) --> 3
print(select("#", "a", "b", "c", "d")) --> 4

setfenv(f, environment)


setfenv(f, myenv)

Sets the current environment to be used by f, which can be a function, userdata, thread or stack level. Level 1 is the current function. Level 0 is the global environment of the current thread. The "env" argument is a table, which effectively becomes the "root" for the environment.

Arguments

  • Argument 1: function - can be a function, userdata, thread or stack level
  • Argument 2: table - the environment

Return

Examples

function f(v)
test = v -- assign to global variable test
end

local myenv = {} -- my local environment table
setfenv(f, myenv) -- change environment for function f
f(42) -- call f with new environment

print(test) --> nil (global test was not changed)
print(myenv.test) --> 42 (test inside myenv was changed)

tonumber(valueToBeConverted)


print(tonumber("4839"))

Converts the value provided to it into a number. If this argument is a number or a convertible string, the tonumber() function returns the converted number. If it is not a number or a convertible string, it will return nil.

Arguments

  • Argument 1: value - the value we want to attempt to convert to a number

Return

  • value: (integer or nil) - returns an integer when successful, nil when not

Examples

mynumber1 = 400
mystring1 = " This is a noncontible string"
mystring2 = "4839"
nilvlaue = nil
tableValue = {2, 3, 5, "49"}

--will return the original number
print(tonumber(mynumber1)) --> 400

--will return nil because this is inconvertible string
print(tonumber(mystring1)) --> nil

--will return the number equivalent of this string
print(tonumber(mystring2)) --> 4839

--returns nil, because data type nil can't convert
print(tonumber(nilvlaue)) --> nil

--converting the whole of the table will fail
print(tonumber(tableValue)) --> nil

--converting a particular convertible element works
print(tonumber(tableValue[4])) --> 49

tostring(value)


print(tostring(45))

Converts a value, usually number, to string.

Arguments

  • Argument 1: value - this is going to get converted to a string data type

Return

  • value: (string) - argument 1 turned into a string

Examples

a = 45
print(tostring(a))

Lua Script Example

version = 16*tonumber(ver:sub(1,1))+tonumber(ver:sub(-1))

type(argument)


print(type(val))

Returns the data type of the argument.

Arguments

  • Argument 1: variable or value - what we want to find the data type of

Return

  • value: (data type) - returns what data type is the argument: nil, boolean, number, string, function, or table

Examples

local tab = {45, "fortyfive", true}
local val = tab[2] --> placing the second value from the table in val variable
print(type(val)) --> string

unpack(table)


print(unpack(t))

Unpacks a table into individual values.

Arguments

  • Argument 1: table - the table we want to extract the individual values from

Return

  • value: values - returns all elements from the given list (table) as individual values

Examples

t = { "the", "quick", "brown" }

print(unpack(t)) --> the quick brown

xpcall(funcToCall, funcErrorHandler)


print(xpcall(f, err))

Calls a function with a custom error handler. If an error occurs in function it is caught and the error-handler is called. Then xpcall returns false, and whatever the error handler returned.

Arguments

  • Argument 1: function - the function we want to call
  • Argument 2: function - what we want to happen if the error is caught

Return

  • value: (boolean and error message) - when the error is caught, it returns false and whatever it is that error-handler returns

Examples

function f()
return "a" + 2 -- will cause error
end

function err(x)
print("err called", x)
return "oh no!"
end

print(xpcall(f, err))

-->
err called [string "Immediate"]:2: attempt to perform arithmetic on a string value
false oh no!

function f2()
return 2 + 2
end

print(xpcall(f2, err)) --> true 4

function f()
return "a" + 2
end

print(xpcall(f, debug.traceback))

-->
false stdin:2: attempt to perform arithmetic on a string value
stack traceback:
stdin:2: in function `f'
[C]: in function `xpcall'
stdin:1: in main chunk
[C]: ?